import { transformSize, fileTypeCorrect } from '@/utils/file/file'
import axios from '@/utils/request'
import { baseURL } from '@/utils/request'

const token = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJubmpjZmoiLCJzY29wZSI6WyJiaXpfc3lzIiwiYmlnX3NjcmVlbiIsInNlcnZlciIsImFsbCJdLCJkZXRhaWwiOnsiaWQiOjgzNjkxMzg3Mjg2MzYzNzUwNCwib3JnSWQiOjE1OTI2NDM3NzQsImNvcnBJZCI6bnVsbCwidXNlcm5hbWUiOiJubmpjZmoiLCJyZWFsTmFtZSI6IuWNl-WugeW4guW4guWcuuebkeedo-euoeeQhuWxgCIsInBhc3N3b3JkIjpudWxsLCJlbmFibGVkIjp0cnVlLCJhcmVhSWQiOjQ1MDEwMCwiYXJlYUxldmVsIjoyLCJvcmdUeXBlIjpudWxsLCJvcmdDb2RlIjoiIiwiZm9yZWlnblVzZXJJZCI6bnVsbCwibGV2ZWwiOm51bGwsInBob25lIjoiMTgzNzM4MTY2ODciLCJyb2xlRmxhZyI6MCwidXNlclR5cGUiOjIsInJvbGVDb2RlTGlzdCI6WyJSMDA1Il0sImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJSMDA1In1dLCJhY2NvdW50Tm9uRXhwaXJlZCI6dHJ1ZSwiY3JlZGVudGlhbHNOb25FeHBpcmVkIjp0cnVlLCJhY2NvdW50Tm9uTG9ja2VkIjp0cnVlfSwiZXhwIjoxNjYxNzgwNTI2LCJhdXRob3JpdGllcyI6WyJSMDA1Il0sImp0aSI6ImQyMWYxZTNhLWJiNWMtNDMxZC1iODI0LTc4MTdjZDdhMWMwMSIsImNsaWVudF9pZCI6Im5pcHZ0LWFwcCJ9.UwKREujwIG_9esRoBj5v69y0tTEwfp83BbYzqvApStM`

const useUpload = () => {
  // 上传前钩子函数
  const onBeforeUpload = (file, failFun, config): boolean => {
    const { allowedFileTypes, maxFileSize } = config
    if (!fileTypeCorrect(file.type, allowedFileTypes)) {
      failFun('文件类型错误，请传入正确的文件类型！')
      return false
    } else if (file.size > maxFileSize) {
      failFun(
        `文件大小超出${transformSize(maxFileSize)}，请上传规定大小内的文件！`
      )
      return false
    }
    return true
  }

  // 获取url
  const getAttachmentUrl = (res, config) => {
    if (res.code === 20000 && res?.data?.data?.sAttachment?.attachPath) {
      const filePath = res.data.data.sAttachment.attachPath
      return `${baseURL}${config.attachmentServer}?token=${token}&pdfPath=${filePath}`
    } else return false
  }

  // 发起上传接口
  const uploadFetch = async (file, config) => {
    const formData = new FormData()
    formData.append(config.fieldName, file)
    const { server, headers, getAttachmentUrl } = config
    const res = await axios({
      url: server,
      method: 'post',
      headers: headers,
      data: formData
    })
    const url = getAttachmentUrl && getAttachmentUrl(res, config)
    if (!url) throw new Error(res.data.code)
    else return url
  }

  // 上传图片回调 file: file对象, succFun(url|string)： 成功回调（插入图片链接到文本中）, failFun(string)：失败回调
  const uploadHandler = (file, succFun, failFun, config) => {
    const { onBeforeUpload, uploadFetch } = config
    if (!onBeforeUpload(file, failFun, config)) return
    uploadFetch(file, config)
      .then((url) => {
        if (!url) throw new Error()
        succFun(url)
      })
      .catch((err) => {
        if (!err.inclueds('20001')) failFun('文件上传失败，请重新上传！')
      })
  }

  return {
    onBeforeUpload,
    uploadHandler,
    uploadFetch,
    getAttachmentUrl
  }
}

export default useUpload
